<template>
  <div class="quality-judge-container">
    <!-- 搜索区域 (Copied structure from LayOutJudge, adapted models/labels) -->
    <div class="search-panel">
      <div class="search-row">
        <div class="search-item">
          <span class="label">时间</span>
          <el-date-picker
            v-model="searchParams.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            class="custom-date-picker"
          />
        </div>
        <div class="search-item range-item">
          <span class="label">出口厚度</span>
          <el-input v-model="searchParams.prodThicknessMin" placeholder="最小值" class="range-input" />
          <span class="separator">-</span>
          <el-input v-model="searchParams.prodThicknessMax" placeholder="最大值" class="range-input" />
        </div>
        <div class="search-item range-item">
          <span class="label">出口宽度</span>
          <el-input v-model="searchParams.prodWidthMin" placeholder="最小值" class="range-input" />
          <span class="separator">-</span>
          <el-input v-model="searchParams.prodWidthMax" placeholder="最大值" class="range-input" />
        </div>
        <div class="search-item range-item">
          <span class="label">原料厚度</span>
          <el-input v-model="searchParams.materialThicknessMin" placeholder="最小值" class="range-input" />
          <span class="separator">-</span>
          <el-input v-model="searchParams.materialThicknessMax" placeholder="最大值" class="range-input" />
        </div>
      </div>
      <div class="search-row">
        <div class="search-item">
          <span class="label">钢种</span>
          <el-select v-model="searchParams.steelGrade" placeholder="请选择" clearable class="custom-select">
            <el-option label="SPHC-LT" value="SPHC-LT" />
            <el-option label="SPHE-H" value="SPHE-H" />
            <el-option label="SPCD" value="SPCD" />
            <el-option label="SPCC" value="SPCC" />
          </el-select>
        </div>
        <div class="search-item">
          <span class="label">冷轧号</span>
          <el-input v-model="searchParams.coldRollNo" placeholder="请输入" class="custom-input" />
        </div>
        <div class="search-item">
          <span class="label">热轧号</span>
          <el-input v-model="searchParams.hotRollNo" placeholder="请输入" class="custom-input" />
        </div>
        <div class="search-item">
          <span class="label">异常筛选</span>
          <el-select v-model="searchParams.thkFlag" placeholder="请选择" clearable class="custom-select">
            <el-option label="全部" value="2" />
            <el-option label="是" value="NO" />
            <el-option label="否" value="OK" />
          </el-select>
        </div>
        <div class="search-actions">
          <button class="btn query-btn" @click="handleSearch">查询</button>
          <button class="btn reset-btn" @click="handleReset">重置</button>
          <button class="btn export-btn">导出</button>
        </div>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-panel">
      <el-table
        :data="pagedTableData"
        style="width: 100%"
        :height="tableHeight"
        border
        highlight-current-row
        :row-class-name="tableRowClassName"
        :header-cell-style="{ background: '#2a5caa', color: '#fff', padding: '8px 10px', textAlign: 'center', fontWeight: 'normal', border: 'none' }"
        :cell-style="{ padding: '8px 10px', textAlign: 'center', color: '#c0c4cc', border: 'none' }"
        :row-style="{ background: '#0f2142' }"
      >
        <el-table-column type="index" label="序号" width="90" align="center" :index="indexMethod" fixed="left" />
        <el-table-column prop="coldCoilID" label="冷轧号" width="160" align="center" />
        <el-table-column prop="hotCoilID" label="热轧号" width="150" align="center" />
        <el-table-column prop="steelGrade" label="钢种" width="100" align="center" />
        <!-- <el-table-column prop="prodSteel" label="产品钢种" width="100" align="center" /> -->
        <el-table-column prop="exThk" label="出口厚度[mm]" width="150" align="center" />
        <el-table-column prop="exWidth" label="出口宽度[mm]" width="150" align="center" />
        <el-table-column prop="exLength" label="出口长度[m]" width="150" align="center" />
        <el-table-column prop="result" label="综合判定" width="110" align="center">
          <template #default="scope">
            <span :class="getOverallResultClass(4, scope.row)">
              {{ scope.row.finalJudgeResult }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="cutFlag" label="后线切除" width="140" align="center" >
          <template #default="scope">
            <span>
              {{ scope.row.cutFlag==0?'否':'是' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="整体评分" width="110" align="center" />
        <el-table-column label="厚度超差长度[m]" align="center">
          <el-table-column prop="devHead" label="头部" width="80" align="center">
            <template #default="scope">
              <span :class="getOverallResultClass(1, scope.row)">
                {{ scope.row.devHead }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="devBody" label="本体" width="100" align="center">
            <template #default="scope">
              <span :class="getOverallResultClass(3, scope.row)">
                {{ scope.row.devBody }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="devTail" label="尾部" width="80" align="center">
            <template #default="scope">
              <span :class="getOverallResultClass(2, scope.row)">
                {{ scope.row.devTail }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="devOverall" label="整体" width="80" align="center" />
        </el-table-column>
        <!-- <el-table-column label="板形超差长度[m]" align="center">
          <el-table-column prop="devHead" label="头部" width="80" align="center">
            <template #default="scope">
              <span>
                {{ scope.row.flataveAlarmLengthHead }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="devBody" label="本体" width="100" align="center">
            <template #default="scope">
              <span>
                {{ scope.row.flataveAlarmLengthMiddle }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="devTail" label="尾部" width="80" align="center">
            <template #default="scope">
              <span>
                {{ scope.row.flataveAlarmLengthTail }}
              </span>
            </template>
          </el-table-column>
        </el-table-column> -->
        <el-table-column prop="ascWaveLengthDs" label="传动侧边浪" width="140" align="center" />
        <el-table-column prop="ascWaveLengthOs" label="操作侧边浪" width="140" align="center" />
        <el-table-column label="板形超差长度[m]" align="center">
          <!-- <el-table-column prop="flataveAlarmLengthHead" label="头部" width="80" align="center" />
          <el-table-column prop="flataveAlarmLengthMiddle" label="本体" width="80" align="center" />
          <el-table-column prop="flataveAlarmLengthTail" label="尾部" width="80" align="center" /> -->
          <el-table-column prop="flatRibbedAvgOppositeSign" label="两侧均值反向长度" width="170" align="center" />
          <el-table-column prop="flatRibbedDiffer10" label="两侧幅值差大于10长度" width="190" align="center" />
          <el-table-column prop="flatBiggerThanMaxLength" label="报警长度" width="120" align="center" />
        </el-table-column>
        <el-table-column prop="ascAlarmDesc" label="板形描述" width="200" align="center" />
        <el-table-column prop="prodEndTime" label="生产完成时间" width="160" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.prodEndTime) }}
          </template>
        </el-table-column>
        <el-table-column label="详情" width="150" fixed="right" align="center">
          <template #default="scope">
            <button class="action-btn select-btn" @click="selectRow(scope.row)">选择</button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-panel">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>

    <!-- 详情区域 -->
    <div v-if="selectedRow && detailData" class="detail-panel">
      <div class="detail-grid">
        <!-- 左侧判定 -->
        <div class="detail-left">
          <div class="judge-block" :class="getJudgeBlockClass(detailData.thickness.result)" @click="handleClick(1)">
            <div class="judge-result">{{ detailData.thickness.result }}</div>
            <div class="judge-content">
              <span class="judge-label">判定内容</span>
              <span class="judge-value">{{ detailData.thickness.content }}</span>
            </div>
            <div class="judge-score">
              <span class="judge-label">评分结果</span>
              <span class="judge-value">{{ detailData.thickness.score }}</span>
            </div>
          </div>
          <div class="judge-block" :class="getJudgeBlockClass(detailData.shape.result)" @click="handleClick(2)">
            <div class="judge-result">{{ detailData.shape.result }}</div>
            <div class="judge-content">
              <span class="judge-label">判定内容</span>
              <span class="judge-value">{{ detailData.shape.content }}</span>
            </div>
            <div class="judge-score">
              <span class="judge-label">评分结果</span>
              <span class="judge-value">{{ detailData.shape.score }}</span>
            </div>
          </div>
        </div>

        <!-- 中间判定 -->
        <div class="detail-middle" v-if="thkJudge">
          <div class="judge-block-small" :class="getJudgeBlockClass(detailData.headPos.result)">
            <!-- <div class="judge-result-small">{{ detailData.headPos.result }}</div> -->
            <div class="judge-details">
              <div class="detail-item">{{ detailData.headPos.category }}</div>
              <div class="detail-item">{{ detailData.headPos.position }}</div>
            </div>
          </div>
          <div class="judge-block-small" :class="getJudgeBlockClass(detailData.bodyPos.result)">
            <!-- <div class="judge-result-small">{{ detailData.bodyPos.result }}</div> -->
            <div class="judge-details">
              <div class="detail-item">{{ detailData.bodyPos.category }}</div>
              <div class="detail-item">{{ detailData.bodyPos.position }}</div>
            </div>
          </div>
          <div class="judge-block-small" :class="getJudgeBlockClass(detailData.tailPos.result)">
            <!-- <div class="judge-result-small">{{ detailData.tailPos.result }}</div> -->
            <div class="judge-details">
              <div class="detail-item">{{ detailData.tailPos.category }}</div>
              <div class="detail-item">{{ detailData.tailPos.position }}</div>
            </div>
          </div>
        </div>

        <!-- 中间判定 -->
        <div class="detail-middle" v-if="platcmResult" style="width: 500px">
          <div class="chart-container" id="platcmLineChartRef" style="width: 100%; height: 300px"></div>
        </div>

        <!-- 右侧图表 -->
        <div class="detail-right detail-section" v-if="thkJudge">
          <div class="section-header">厚度(长度序列)</div>
          <div class="chart-container" ref="lineChartRef"></div>
        </div>

        <div class="detail-right detail-section" v-if="platcmResult">
          <div id="app7" style="width: 99%; height: 300px" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch, onMounted, onBeforeMount, onUnmounted, nextTick } from 'vue';
  import * as echarts from 'echarts/core';
  import { LineChart } from 'echarts/charts';
  import { TooltipComponent, GridComponent, LegendComponent, DataZoomComponent, MarkLineComponent } from 'echarts/components';
  import { CanvasRenderer } from 'echarts/renderers';
  import { thicknessAndLayOutJudgeApi } from '/@/api/thicknessAndLayOutJudge/index';
  import { historyApi } from '/@/api/furnaceTempDynamicCtrl/history'; // Register ECharts componentsimport type { EChartsOption } from 'echarts';
  import { useUserStore } from '/@/store/modules/system/user';
  echarts.use([TooltipComponent, GridComponent, LegendComponent, LineChart, CanvasRenderer, DataZoomComponent, MarkLineComponent]);

  const data = ref([
    { menuName: 'QualityJudge', menuTitle: '酸轧质量综合判别', menuId: '1' },
    { menuName: 'thicknessJudge', menuTitle: '酸轧厚度判别' },
    { menuName: 'LayOutJudge', menuTitle: '酸轧板形判别' },
    { menuName: 'ThickNessLayOutAbnormal', menuTitle: '酸轧厚度、板形异常明细' },
    { menuName: 'ThickNessLayOutStatistics', menuTitle: '酸轧厚度、板形优化统计分析' },
    { menuName: 'MaterialStandards', menuTitle: '原料规范标准表' },
    { menuName: 'OrderAlert', menuTitle: '订单宽度厚度预警' },
  ]);

  // --- Interfaces ---
  interface SearchParams {
    dateRange: Date[];
    prodThicknessMin: string;
    prodThicknessMax: string;
    prodWidthMin: string;
    prodWidthMax: string;
    materialThicknessMin: string;
    materialThicknessMax: string;
    steelGrade: string;
    coldRollNo: string;
    hotRollNo: string;
    thkFlag: string;
  }

  interface FindDataParams {
    prodThicknessMin: string;
    prodThicknessMax: string;
    materialWidthMin: string;
    materialWidthMax: string;
    materialThicknessMin: string;
    materialThicknessMax: string;
    steelGrade: string;
    coldRollNo: string;
    hotRollNo: string;
    thkFlag: string;
    startDate?: string;
    endDate?: string;
    pageIndex: string;
    pageSize: string;
  }

  interface TableRow {
    id: number;
    coldCoilID: string;
    hotCoilID: string;
    hotRollNo: string;
    steelGrade: string;
    prodSteelGrade: string;
    exportThickness: number;
    exportWidth: number;
    exportLength: number;
    overallResult: 'OK' | 'NO';
    overallScore: number;
    devHead: number;
    devBody: number;
    devTail: number;
    devOverall: number;
    thkFlag: string;
    clostFlag: number;
    scoreThick: number;
    scoreFlat: number;
    flataveAlarmLengthHead: number;
    flataveAlarmLengthMiddle: number;
    flataveAlarmLengthTail: number;
    prodEndTime: string;
    exThk: string;
    exWidth: string;
    exLength: string;
    prodSteel: string;
    thkUpper: number;
    thkLower: number;
    judgeResult: number;
    cutFlag:number;
  }

  interface JudgeDetail {
    result: 'OK' | 'NO';
    content?: string;
    score?: number;
    category?: string;
    position?: number | string;
  }

  interface DetailData {
    thickness: JudgeDetail;
    shape: JudgeDetail;
    headPos: JudgeDetail;
    bodyPos: JudgeDetail;
    tailPos: JudgeDetail;
  }

  interface RecordTableRow {
    coldCoilID: string;
    hotCoilID: string;
    steelGrade: string;
    exThk: string;
    exWidth: string;
    thkHeadToleAbsLen: string;
    thkMidToleAbsLen: string;
    thkTailToleAbsLen: string;
    thkHeadHitRate: string;
    thkMidHitRate: string;
    thkTailHitRate: string;
    enThk: string;
    enWidth: string;
    prodSteel: string;
    judgeResult: number;
    thkUpper: number;
    thkLower: number;
    cutFlag:number;
  }

  // --- Reactive State ---
  const searchParams = reactive<SearchParams>({
    dateRange: [],
    prodThicknessMin: '',
    prodThicknessMax: '',
    prodWidthMin: '',
    prodWidthMax: '',
    materialThicknessMin: '',
    materialThicknessMax: '',
    steelGrade: '',
    coldRollNo: '',
    hotRollNo: '',
    thkFlag: 'NO',
  });

  // --- Mock Table Data ---
  const allTableData = ref<TableRow[]>([]);
  const graphThkData = ref<number[]>([]);
  const graphSpeedData = ref<number[]>([]);
  const tableHeight = ref('calc(100vh - 180px)');
  const platcmResult = ref(false);
  const thkJudge = ref(false);
  let clickChanel = 13;
  let formData = '';

  // --- Pagination ---
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: allTableData.value.length,
  });

  const pagedTableData = computed(() => {
    return allTableData.value;
  });

  const indexMethod = (index: number) => {
    return (pagination.currentPage - 1) * pagination.pageSize + index + 1;
  };

  const handleSizeChange = (val: number) => {
    pagination.pageSize = val;
    fetchTableData();
  };

  const handleCurrentChange = (val: number) => {
    pagination.currentPage = val;
    fetchTableData();
  };

  // --- Row Selection & Detail Data ---
  const selectedRow = ref<TableRow | null>(null);
  const plateCurveData = ref([]);
  let rememberA = <any>[];
  let rememberB = <any>[];
  let rememberC = <any>[];
  let rememberR = <any>[];
  const dialogVisible2 = ref(false);
  const dialogTitle2 = ref(''); //修改Y轴
  let sum = <any>1;
  const echart = {
    max1: 30,
    min1: -10,
    max2: 30,
    min2: -30,
    // max3: 30,
    // min3: -30,
    max5: 30,
    min5: -30,
    max18: 25,
    min18: -25,
  };

  const detailData = computed<DetailData | null>(() => {
    if (!selectedRow.value) return null;
    const seed = selectedRow.value;
    console.log('seed', seed);
    const thicknessOk = seed.thkJudge == 'OK'; // Higher chance for thickness OK
    const shapeOk = seed.flatJudge == 'OK';
    return {
      thickness: {
        result: thicknessOk ? 'OK' : 'NO',
        content: '厚度',
        score: parseFloat(seed.scoreThick.toFixed(1)),
      },
      shape: {
        result: shapeOk ? 'OK' : 'NO',
        content: '板形',
        score: parseFloat(seed.scoreFlat.toFixed(1)),
      },
      headPos: {
        result: selectedRow.value.devHead <= 3 ? 'OK' : 'NO',
        category: '头部超差位置',
        position: selectedRow.value.devHead > 0 ? selectedRow.value.devHead : '-',
      },
      bodyPos: {
        result: 'OK',
        category: '本体超差位置',
        position: selectedRow.value.devBody > 0 ? selectedRow.value.devBody : '-',
      },
      tailPos: {
        result: selectedRow.value.devTail <= 2 ? 'OK' : 'NO',
        category: '尾部超差位置',
        position: selectedRow.value.devTail > 0 ? selectedRow.value.devTail : '-',
      },
      headFlatave: {
        result: selectedRow.value.flataveAlarmLengthHead <= 3 ? 'OK' : 'NO',
        category: '头部超差位置',
        position: selectedRow.value.flataveAlarmLengthHead > 0 ? selectedRow.value.flataveAlarmLengthHead : '-',
      },
      bodyFlatave: {
        result: 'OK',
        category: '本体超差位置',
        position: selectedRow.value.flataveAlarmLengthMiddle > 0 ? selectedRow.value.flataveAlarmLengthMiddle : '-',
      },
      tailFlatave: {
        result: selectedRow.value.flataveAlarmLengthTail <= 2 ? 'OK' : 'NO',
        category: '尾部超差位置',
        position: selectedRow.value.flataveAlarmLengthTail > 0 ? selectedRow.value.flataveAlarmLengthTail : '-',
      },
    };
  });

  const selectRow = (row: TableRow) => {
    selectedRow.value = row;
    getThickData(selectedRow.value);
    tableHeight.value = '210px';
    thkJudge.value = true;
    platcmResult.value = false;
    console.log('选中行:', row);
    findAll4(row.coldCoilID, row);
  };

  const tableRowClassName = ({ row }: { row: TableRow }) => {
    if (selectedRow.value) {
      console.log('11111');
      return 'selected-row';
    }
    return '';
  };

  // Helper for conditional styling
  const getOverallResultClass = (type: any, result: any) => {
    if (type == 1) {
      if (result.devHead > 5) {
        return 'result-no';
      }
    } else if (type == 2) {
      if (result.devTail > 3) {
        return 'result-no';
      }
    } else if (type == 3) {
      if (result.devBody > 0) {
        return 'result-no';
      }
    } else {
      console.log('result' + result);
      return result.finalJudgeResult === 'OK' ? 'result-ok' : 'result-no';
    }
  };
  const getJudgeBlockClass = (result: 'OK' | 'NO') => {
    return result === 'OK' ? 'judge-ok' : 'judge-no';
  };

  // --- ECharts ---
  const lineChartRef = ref<HTMLElement | null>(null);
  let lineChartInstance: echarts.ECharts | null = null;
  let toolbox = {
    iconStyle: {
      borderColor: '#fff',
    },
    feature: {
      dataView: {
        show: true,
        lang: ['数据视图', '关闭', '导出Excel'],
        //optionToContent为重画表格的函数
        optionToContent: function (opt: any) {
          //axisData是你想定义的表格第一列的数据，我这里设置为柱形图的x轴数据
          var axisData = opt.xAxis[0].data;
          //tAxis[0]为你想定义的表格第一行的数据
          var txisData = opt.series[0].data;
          // console.log(opt)
          var series = opt.series;
          //表头
          var tdHeads = '<td  style="padding: 0 10px"></td>';
          var tdBodys = '';
          var nameData = txisData;
          // console.log(nameData)
          for (var i = 0; i < nameData.length; i++) {
            tdHeads += '<td style="padding: 0 10px">' + nameData[i] + '</ td >';
          }
          var table =
            '<table id="Mytable" border="1" class="table table-bordered table-striped table-hover" style="width:100%;text-align:center;color: #000;" ><tbody><tr>' +
            tdHeads +
            ' </tr>';
          for (var i = 0, l = axisData.length; i < l; i++) {
            for (var j = 0; j < series.length; j++) {
              if (series[j].data != undefined) {
                var temp = series[j].data[i];
                if (temp != null && temp != undefined) {
                  tdBodys += '<td>' + temp + '</td>';
                } else {
                  tdBodys += '<td></td>';
                }
              }
            }
            table += '<tr><td style="padding: 0 10px">' + axisData[i] + '</td>' + tdBodys + '</tr>';
            tdBodys = '';
          }
          table += '</tbody></table>';
          return table;
        },
        contentToOption: function (HTMLDomElement, opt) {
          let et = XLSX.utils.table_to_book(document.getElementById('Mytable'));
          let etout = XLSX.write(et, {
            bookType: 'xlsx',
            bookSST: true,
            type: 'array',
          });
          try {
            saveAs(
              new Blob([etout], {
                type: 'application/octet-stream',
              }),
              'echarts数据' + '-' + new Date().toLocaleString() + '.xlsx'
            );
          } catch (e) {}
          return etout;
        },
      },
      magicType: { show: true },
      restore: { show: true },
      saveAsImage: { show: true },
      // dataZoom: {show: true},
    },
  };

  const oneSidedAlarmPos = ref([]);
  const bothSidedAlarmPos = ref([]);
  const bothSidedMultiAlarmPos = ref([]);
  const unsymRibbedAlarmPos = ref([]);
  const unsymSidedDiffAlarmPos = ref([]);
  const length = ref<any>();

  const yAxisData = [1, 2, 3, 4, 5];
  const colors = ['#ff4d4f', '#e6a23c', '#67c23a', '#409eff', '#9b59b6'];

  const platcmOption = computed(() => ({
    tooltip: {
      trigger: 'axis',
      formatter: function (params: any | any[]) {
        if (!Array.isArray(params)) params = [params];
        let result = '';
        // 这里 allSeriesData 必须在 computed 里声明，能访问到5个ref
        const allSeriesData = [
          oneSidedAlarmPos.value,
          bothSidedAlarmPos.value,
          bothSidedMultiAlarmPos.value,
          unsymRibbedAlarmPos.value,
          unsymSidedDiffAlarmPos.value,
        ];
        let next = '';
        params.forEach((item: any) => {
          const seriesData = allSeriesData[item.seriesIndex] || [];
          // 先取所有x值并去重
          const allX = Array.from(new Set(seriesData.map((d: any) => d[0]))).sort((a: number, b: number) => a - b);
          if (allX.length === 0) {
            result += `${item.seriesName}：无数据<br/>`;
            return;
          }
          let ranges = [];
          let start = allX[0],
            end = allX[0];
          for (let i = 1; i < allX.length; i++) {
            if (allX[i] === end + 1) {
              end = allX[i];
            } else {
              ranges.push([start, end]);
              start = end = allX[i];
            }
          }
          ranges.push([start, end]);

          let currentX = item.data[0];
          let rangeStr = '';
          for (let [s, e] of ranges) {
            if (currentX >= s && currentX <= e) {
              rangeStr = s === e ? `${s}` : `${s}-${e}`;
              break;
            }
          }
          // 只显示一次当前x对应的区间（去重）
          if (next != rangeStr) {
            result += `${item.seriesName}：${rangeStr}<br/>`;
          }
          next = rangeStr;
          console.log('result' + result);
        });
        return result;
      },
    },
    legend: {
      data: ['单边浪超限位置', '双边浪超限位置', '对称复合肋浪超限位置', '非对称勒浪超限位置', '不对称边浪超限位置'],
      textStyle: { color: '#fff' },
    },
    xAxis: {
      type: 'value',
      min: 0,
      max: length.value,
      name: '(m)',
      axisLabel: { show: true, color: '#fff' },
      axisLine: { show: true, lineStyle: { color: '#fff' } },
      axisTick: { show: true },
      splitLine: { show: false },
    },
    yAxis: {
      type: 'category',
      name: '',
      data: yAxisData,
      axisLabel: { show: true, color: '#fff' },
      axisLine: { show: true, lineStyle: { color: '#fff' } },
      axisTick: { show: true },
      splitLine: { show: true },
    },
    series: [
      {
        name: '单边浪超限位置',
        data: oneSidedAlarmPos.value,
        type: 'line',
        symbol: 'triangle',
        symbolSize: 20,
        itemStyle: {
          color: colors[0],
          borderWidth: 3,
          borderColor: '#fff',
        },
        lineStyle: {
          color: colors[0],
          width: 4,
          type: 'dashed',
        },
      },
      {
        name: '双边浪超限位置',
        data: bothSidedAlarmPos.value,
        type: 'line',
        symbol: 'triangle',
        symbolSize: 20,
        itemStyle: {
          color: colors[1],
          borderWidth: 3,
          borderColor: '#fff',
        },
        lineStyle: {
          color: colors[1],
          width: 4,
          type: 'dashed',
        },
      },
      {
        name: '对称复合肋浪超限位置',
        data: bothSidedMultiAlarmPos.value,
        type: 'line',
        symbol: 'triangle',
        symbolSize: 20,
        itemStyle: {
          color: colors[2],
          borderWidth: 3,
          borderColor: '#fff',
        },
        lineStyle: {
          color: colors[2],
          width: 4,
          type: 'dashed',
        },
      },
      {
        name: '非对称肋浪超限位置',
        data: unsymRibbedAlarmPos.value,
        type: 'line',
        symbol: 'triangle',
        symbolSize: 20,
        itemStyle: {
          color: colors[3],
          borderWidth: 3,
          borderColor: '#fff',
        },
        lineStyle: {
          color: colors[3],
          width: 4,
          type: 'dashed',
        },
      },
      {
        name: '不对称边浪超限位置',
        data: unsymSidedDiffAlarmPos.value,
        type: 'line',
        symbol: 'triangle',
        symbolSize: 20,
        itemStyle: {
          color: colors[4],
          borderWidth: 3,
          borderColor: '#fff',
        },
        lineStyle: {
          color: colors[4],
          width: 4,
          type: 'dashed',
        },
      },
    ],
  }));

  const generateChartData = (params: RecordTableRow) => {
    let length = graphSpeedData.value.length;
    const upperLimit = Array.from({ length }, (_, i) => params.thkUpper);
    const lowerLimit = Array.from({ length }, (_, i) => params.thkLower);
    console.log(upperLimit);
    return { upperLimit, lowerLimit };
  };

  const lineChartOption = computed<any>(() => {
    if (!selectedRow.value) return {};
    const { upperLimit, lowerLimit } = generateChartData(selectedRow.value);
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' },
      },
      legend: {
        data: ['厚度', '速度', '厚度上限', '厚度下限'],
        textStyle: { color: '#c0c4cc' },
      },
      grid: { left: '5%', right: '5%', bottom: '10%', containLabel: true },
      xAxis: {
        type: 'category',
        axisLabel: { color: '#c0c4cc' },
        name: '(m)',
        nameLocation: 'end',
        nameTextStyle: { color: '#c0c4cc', align: 'right', verticalAlign: 'top', padding: [10, 0, 0, 0] },
        // 自适应数据范围，无需min/max
      },
      yAxis: [
        {
          type: 'value',
          name: 'mm',
          position: 'left',
          axisLabel: { color: '#c0c4cc' },
          splitLine: { lineStyle: { color: '#3a5a8a' } },
          min: 0.4,
          // 自适应数据范围，无需min/max
        },
        {
          type: 'value',
          name: 'm/min',
          position: 'right',
          axisLabel: { color: '#c0c4cc' },
          splitLine: { show: false },
          // 自适应数据范围，无需min/max
        },
      ],
      dataZoom: [
        {
          type: 'inside',
          start: 0,
          end: 100,
        },
        {
          start: 0,
          end: 100,
          handleIcon:
            'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
          handleSize: '80%',
          handleStyle: {
            color: '#fff',
            shadowBlur: 3,
            shadowColor: 'rgba(0, 0, 0, 0.6)',
            shadowOffsetX: 2,
            shadowOffsetY: 2,
          },
          textStyle: { color: '#c0c4cc' },
          borderColor: '#3a5a8a',
        },
      ],
      series: [
        {
          name: '厚度',
          type: 'line',
          yAxisIndex: 0,
          data: [],
          smooth: true,
          showSymbol: false,
          itemStyle: { color: '#ff4d4f' },
          markLine: {
            silent: true,
            symbol: ['none', 'none'],
            lineStyle: { type: 'dashed', color: '#ccc' },
            data: [
              { yAxis: upperLimit, label: { formatter: '厚度上限:{c}', position: 'insideEndTop' } },
              { yAxis: lowerLimit, label: { formatter: '厚度下限:{c}', position: 'insideEndBottom' } },
            ],
          },
        },
        {
          name: '速度',
          type: 'line',
          yAxisIndex: 1,
          data: [],
          smooth: true,
          showSymbol: false,
          itemStyle: { color: '#e6a23c' },
        },
        { name: '厚度上限', type: 'line', data: [], smooth: true, showSymbol: false, lineStyle: { type: 'dashed', color: '#0000FF' } },
        { name: '厚度下限', type: 'line', data: [], smooth: true, showSymbol: false, lineStyle: { type: 'dashed', color: '#008000' } },
      ],
    };
  });

  const initChart = () => {
    try {
      // 先销毁旧的
      if (lineChartInstance) {
        lineChartInstance.dispose();
        lineChartInstance = null;
      }
      if (lineChartRef.value) {
        lineChartInstance = echarts.init(lineChartRef.value);
        lineChartInstance.setOption(lineChartOption.value);
      }
      // platcmLineChartRef 的初始化逻辑保持不变
    } catch (error) {
      console.error('ECharts initialization failed:', error);
    }
  };

  const updateChart = () => {
    if (!selectedRow.value || !lineChartInstance) return;
    try {
      lineChartInstance.setOption(lineChartOption.value);
    } catch (error) {
      console.error('ECharts update failed:', error);
    }
  };

  const resizeChart = () => {
    lineChartInstance?.resize();
  };

  // 时间格式化函数
  const formatDateTime = (dateTime: string | null | undefined): string => {
    if (!dateTime) return '-';

    try {
      // 如果是数字格式的时间戳，先转换为字符串
      const dateStr = String(dateTime);

      // 处理不同格式的时间字符串
      let date: Date;

      // 如果是纯数字格式 (YYYYMMDDHHmmss)
      if (/^\d{14}$/.test(dateStr)) {
        const year = parseInt(dateStr.substring(0, 4));
        const month = parseInt(dateStr.substring(4, 6)) - 1;
        const day = parseInt(dateStr.substring(6, 8));
        const hour = parseInt(dateStr.substring(8, 10));
        const minute = parseInt(dateStr.substring(10, 12));
        const second = parseInt(dateStr.substring(12, 14));
        date = new Date(year, month, day, hour, minute, second);
      }
      // 如果是标准日期时间格式
      else if (dateStr.includes('-') || dateStr.includes('/')) {
        date = new Date(dateStr);
      }
      // 其他格式尝试直接解析
      else {
        date = new Date(dateStr);
      }

      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return '-';
      }

      // 格式化为 YYYY-MM-DD HH:mm:ss
      const pad = (num: number) => num.toString().padStart(2, '0');
      return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(
        date.getSeconds()
      )}`;
    } catch (error) {
      console.error('时间格式化错误:', error);
      return '-';
    }
  };

  function handleClick(type: any) {
    if (type == 1) {
      thkJudge.value = true;
      platcmResult.value = false;
      if (lineChartInstance) {
        lineChartInstance.dispose();
        lineChartInstance = null;
      }
      nextTick(() => {
        initChart();
      });
    } else if (type == 2) {
      thkJudge.value = false;
      platcmResult.value = true;
      if (platcmChartInstance) {
        platcmChartInstance.dispose();
        platcmChartInstance = null;
      }
      if (selectedRow.value) {
        nextTick(() => {
          findAll4(selectedRow.value.coldCoilID, selectedRow.value);
        });
      }
      getPlatcmData().then(() => {
        nextTick(() => {
          initPlatcmChart(platcmOption.value);
        });
      });
    }
  }

  watch(selectedRow, (newVal) => {
    if (newVal && thkJudge.value) {
      nextTick(() => {
        if (lineChartInstance) {
          lineChartInstance.dispose();
          lineChartInstance = null;
        }
        initChart();
      });
    }
  });
  let platcmChartInstance: echarts.ECharts | null = null;

  onBeforeMount(() => {
    useUserStore().setTagNav(data.value);
    fetchTableData();
  }),
    onMounted(() => {
      if (selectedRow.value) {
        nextTick(initChart);
      }
      window.addEventListener('resize', resizeChart);
    });

  async function getPlatcmData() {
    let params = [
      'one_sided_alarm_pos',
      'both_sided_alarm_pos',
      'both_sided_multi_alarm_pos',
      'unsym_ribbed_alarm_pos',
      'unsym_sided_diff_alarm_pos',
    ];

    const graphParam = {
      line: 'TCM2280',
      extid: [selectedRow.value.coldCoilID],
      model: params,
    };
    const response = await historyApi.getgraphData(graphParam);
    const model = response.data.data.model[0];
    oneSidedAlarmPos.value = model.one_sided_alarm_pos ? model.one_sided_alarm_pos.map((x) => [x, 0]) : [];
    bothSidedAlarmPos.value = model.both_sided_alarm_pos ? model.both_sided_alarm_pos.map((x) => [x, 1]) : [];
    bothSidedMultiAlarmPos.value = model.both_sided_multi_alarm_pos ? model.both_sided_multi_alarm_pos.map((x) => [x, 2]) : [];
    unsymRibbedAlarmPos.value = model.unsym_ribbed_alarm_pos ? model.unsym_ribbed_alarm_pos.map((x) => [x, 3]) : [];
    unsymSidedDiffAlarmPos.value = model.unsym_sided_diff_alarm_pos ? model.unsym_sided_diff_alarm_pos.map((x) => [x, 4]) : [];
    console.log('oneSidedAlarmPos' + oneSidedAlarmPos.value);
    if (platcmChartInstance) {
      platcmChartInstance.setOption(platcmOption.value, true);
    }
  }

  const fetchTableData = async () => {
    try {
      const formatDate = (date: string | Date | null | undefined): string | undefined => {
        if (!date) return undefined;
        if (date instanceof Date) {
          const pad = (num: number) => num.toString().padStart(2, '0');
          return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}${pad(date.getHours())}${pad(date.getMinutes())}${pad(
            date.getSeconds()
          )}`;
        }
        return date;
      };

      if (searchParams.dateRange == null) {
        searchParams.dateRange = [];
      }

      const params: FindDataParams = {
        prodThicknessMin: searchParams.prodThicknessMin,
        prodThicknessMax: searchParams.prodThicknessMax,
        materialWidthMin: searchParams.materialWidthMax,
        materialWidthMax: searchParams.materialWidthMax,
        materialThicknessMin: searchParams.materialThicknessMin,
        materialThicknessMax: searchParams.materialThicknessMax,
        steelGrade: searchParams.steelGrade,
        coldRollNo: searchParams.coldRollNo,
        hotRollNo: searchParams.hotRollNo,
        thkFlag: searchParams.thkFlag == '2' ? '' : searchParams.thkFlag,
        startDate: formatDate(searchParams.dateRange[0]),
        endDate: formatDate(searchParams.dateRange[1]),
        pageIndex: String(pagination.currentPage),
        pageSize: String(pagination.pageSize),
      };

      Object.keys(params).forEach((key) => {
        if (params[key as keyof FindDataParams] === undefined) {
          delete params[key as keyof FindDataParams];
        }
      });

      const response = await thicknessAndLayOutJudgeApi.findByPage(params);

      console.log(response);

      if (response && response.data && Array.isArray(response.data.data.records)) {
        const responsePayload = response.data.data;
        const records = responsePayload.records;

        const mappedData = records.map((record: RecordTableRow) => {
          return {
            devHead: record.thkHeadToleAbsLen,
            devBody: record.thkMidToleAbsLen,
            devTail: record.thkTailToleAbsLen,
            devOverall: record.thkHeadToleAbsLen + record.thkMidToleAbsLen + record.thkTailToleAbsLen,
            rateHead: record.thkHeadHitRate,
            rateMid: record.thkMidHitRate,
            rateTail: record.thkTailHitRate,
            materialThickness: record.enThk,
            materialWidth: record.enWidth,
            coldCoilID: record.coldCoilID,
            hotCoilID: record.hotCoilID,
            prodSteel: record.prodSteel,
            result: record.judgeResult == 0 ? 'OK' : 'NO',
            thkUpper: record.thkUpper,
            thkLower: record.thkLower,
            ...record,
          };
        });

        allTableData.value = mappedData;
        pagination.total = responsePayload.total;
        ElMessage.success(responsePayload.msg || '查询成功');
      } else {
        ElMessage.info(response?.data?.msg || '未查询到数据或响应格式不正确');
        allTableData.value = [];
        pagination.total = 0;
      }
    } catch (error: any) {
      console.error('获取数据失败:', error);
      ElMessage.error(error.response?.data?.msg || error.message || '获取数据失败');
      allTableData.value = [];
      pagination.total = 0;
    }
  };

  const getThickData = async (row: any) => {
    const graphParam = {
      line: 'TCM2280',
      extid: [row.coldCoilID],
      curve: ['tcm_exs5_thk_act', 'tcm_s5_strip_speed_act'],
    };
    const response = await historyApi.getgraphData(graphParam);
    graphThkData.value = response.data.data.curve[0].tcm_exs5_thk_act;
    graphSpeedData.value = response.data.data.curve[0].tcm_s5_strip_speed_act;
    length.value = response.data.data.curve[0].end;
    lineChartOption.value.series[0].data = graphThkData.value;
    lineChartOption.value.series[1].data = graphSpeedData.value;

    const { upperLimit, lowerLimit } = generateChartData(selectedRow.value);
    lineChartOption.value.series[2].data = upperLimit;
    lineChartOption.value.series[3].data = lowerLimit;

    updateChart();
  };

  onUnmounted(() => {
    window.removeEventListener('resize', resizeChart);
    lineChartInstance?.dispose();
  });

  // --- Handlers ---
  const handleSearch = () => {
    pagination.currentPage = 1;
    fetchTableData();
  };

  const handleReset = () => {
    Object.keys(searchParams).forEach((key) => {
      const typedKey = key as keyof SearchParams;
      if (typedKey === 'dateRange') {
        searchParams[typedKey] = [];
      } else {
        searchParams[typedKey] = '';
      }
    });
    selectedRow.value = null;
    console.log('重置参数');
  };

  async function findAll4(extid: any, row: any) {
    let params = [
      'tcm_shape_channe_0',
      'tcm_shape_channe_1',
      'tcm_shape_channe_2',
      'tcm_shape_channe_4',
      'tcm_shape_channe_5',
      'tcm_shape_channe_6',
      'tcm_shape_channe_7',
      'tcm_shape_channe_8',
      'tcm_shape_channe_9',
      'tcm_shape_channe_10',
      'tcm_shape_channe_11',
      'tcm_shape_channe_12',
      'tcm_shape_channe_13',
      'tcm_shape_channe_14',
      'tcm_shape_channe_15',
      'tcm_shape_channe_16',
      'tcm_shape_channe_17',
      'tcm_shape_channe_18',
      'tcm_shape_channe_19',
      'tcm_shape_channe_20',
      'tcm_shape_channe_21',
      'tcm_shape_channe_22',
      'tcm_shape_channe_23',
      'tcm_shape_channe_24',
      'tcm_shape_channe_25',
      'tcm_shape_channe_26',
      'tcm_shape_channe_27',
      'tcm_shape_channe_28',
      'tcm_shape_channe_29',
      'tcm_shape_channe_30',
      'tcm_shape_channe_31',
      'tcm_shape_channe_32',
      'tcm_shape_channe_33',
      'tcm_shape_channe_34',
      'tcm_shape_channe_35',
      'tcm_shape_channe_36',
      'tcm_shape_channe_37',
      'tcm_shape_channe_38',
      'tcm_shape_channe_39',
      'tcm_shape_channe_40',
      'tcm_shape_channe_41',
      'tcm_shape_channe_42',
      'tcm_shape_channe_43',
      'tcm_shape_channe_44',
      'tcm_shape_channe_45',
      'tcm_shape_channe_46',
      'tcm_shape_channe_47',
      'tcm_shape_channe_48',
      'tcm_shape_channe_49',
      'tcm_shape_channe_50',
      'tcm_shape_channe_51',
      'tcm_shape_channe_52',
      'tcm_shape_channe_53',
      'tcm_shape_channe_54',
      'tcm_shape_channe_55',
      'tcm_shape_channe_56',
      'tcm_shape_channe_57',
      'tcm_shape_channe_58',
      'tcm_shape_channe_59',
      'tcm_shape_channe_60',
      'tcm_shape_channe_61',
      'tcm_shape_channe_62',
      'tcm_shape_channe_63',
      'tcm_s5_strip_speed_act',
    ];

    const graphParam = {
      line: 'TCM2280',
      extid: [extid],
      curve: params,
    };
    const response = await historyApi.getgraphData(graphParam);
    //绘制2D板形图曲线-长度序列
    if (response.data.data.curve[0].tcm_shape_channe_32) {
      let filteredObj = [];

      const newItem = Object.fromEntries(
        Object.entries(response.data.data.curve[0]).filter(([key, value]) => {
          if (Array.isArray(value)) {
            value.some((num) => num !== 0);
          }
          return value;
        })
      );
      filteredObj.push({ ...newItem });

      console.log('filteredObj' + filteredObj);

      echart_test7(filteredObj);
      plateCurveData.value = response.data.data.curve[0];
    } else {
      plateCurveData.value = [];
      echarts_no('app7');
    }
  }

  function echart_test7(datas10: any) {
    var need_x11 = [];
    console.log(datas10);
    for (var i = 0; i < datas10[0].tcm_shape_channe_11.length; i++) {
      need_x11.push(i + 1);
    }
    let res: any = [];
    let max = 0; //这个值用于计算两边通道有多个全为0的通道个数，最后用来补齐拟合曲线的个数
    Object.entries(datas10[0]).forEach(([key, value]) => {
      const macthReq = /tcm_shape_channe_(\d+)$/.exec(key);
      if (!macthReq || value.every((i) => i === 0)) return; //去掉所有通道数组全为0的通道
      const index = Number(macthReq[1]); //根据曲线名称例如channel_26,用正则获取通道号数字
      max = Math.max(max, index); //取最大的且通道数据不全为0的通道号

      value.forEach((v: any, i: any) => {
        res.push([i, index - 1, v]); //组装板形图的数据
        // 第一个元素代表X轴、第二个Y轴、第三个是值
      });
    });
    // console.log(res)
    // 取第一米的各通道数据，用于默认显示第一米板形截面图
    let Tuglie = [];
    for (var x = 0; x < res.length; x++) {
      if (res[x]['0'] == 1) {
        Tuglie.push(res[x]);
      }
    }
    // 将第一米界面的数据处理，排序过后从二维数组中，取出对应板形值，放置在一元数组，用来绘制截面图
    let list: any = [];
    // console.log(this.Tuglie.sort((a, b) => a[1] - b[1]))
    list = Tuglie.sort((a, b) => a[1] - b[1])
      .map((item) => {
        return item[2];
      })
      // .reverse()
      .join(',');
    var myChart = echarts.init(document.getElementById('app7')); //将配置注入到html中定义的容器
    // prettier-ignore
    let days = [
    'c_0', 'c_1',
    'c_2', 'c_3', 'c_4', 'c_5','c_6', 'c_7', 'c_8', 'c_9','c_10',
    'c_11', 'c_12', 'c_13', 'c_14','c_15', 'c_16', 'c_17', 'c_18','c_19',
    'c_20', 'c_21', 'c_22', 'c_23','c_24','c_25','c_26','c_27','c_28','c_29',
    'c_30','c_31','c_32','c_33','c_34','c_35','c_36','c_37','c_38','c_39','c_40',
    'c_41','c_42','c_43','c_44','c_45','c_46','c_47','c_48','c_49','c_50','c_51',
    'c_52','c_53','c_54','c_55','c_56','c_57','c_58','c_59','c_60','c_61','c_62','c_63'
  ];
    //计算单侧边部通道需要补0的个数
    let listMxsMin = days.length - max;
    let a1: any = [];
    for (var i = 0; i < listMxsMin; i++) {
      a1.push('0.00');
    }
    //拟合方程开始
    let newX = list.split(',');
    let zeroPoint = parseInt(newX.length / 2); //取所有通道中间点
    let leftX = [];
    let rightX = [];
    //存放X正半轴
    for (let i = 0; i < zeroPoint; i++) {
      leftX.push(parseFloat(((2 * i + 1) / newX.length).toFixed(2)));
    }
    //存放X负半轴
    for (let i = 1; i <= zeroPoint; i++) {
      rightX.push(parseFloat(((-2 * i + 1) / newX.length).toFixed(2)));
    }
    //拼接成一个完整的X轴
    let allXaxis = rightX.reverse().concat(leftX);
    let allYaxis = [];
    allXaxis.forEach((item, index) => {
      // 计算a*x平方+b*x+c
      allYaxis.push(parseFloat(rememberA[0] * Math.pow(item, 2) * 1 + rememberB[0] * item * 1 + rememberC[0] * 1).toFixed(2) * 1);
    });
    // 最后补齐两侧通道为0的通道的数据，保证元素个数与通道号一致
    for (let i = 0; i < listMxsMin; i++) {
      allYaxis.push('');
      allYaxis.unshift('');
    }

    let titleA = rememberA[0];
    let titleB = rememberB[0];
    let titleC = rememberC[0];
    let titleR = rememberR[0];
    // 取第一米的板形截面数据，并按照升序排列，保证通道后由小到大
    var listST = [];
    listST = res
      .filter((i) => i[0] === 1)
      .sort((a: any, b: any) => a[1] - b[1])
      .map((i) => i[2]);
    // 补齐板形截面柱状图两侧通道个数，保证元素个数与通道号一致
    var lnewaWa = a1.join() + ',' + listST + ',' + a1.join();
    find_singleChanel(formData, clickChanel);
    var option = {
      title: {
        text: '板形仪通道号(长度序列)' + formData,
        textStyle: {
          color: '#ccc',
          fontStyle: 'normal',
          fontWeight: 'bold',
          fontFamily: 'sans-serif',
          fontSize: 18,
        },
      },
      tooltip: {
        position: 'top',
      },
      grid: {
        left: '3%',
        right: '6%',
        containLabel: true,
      },
      // dataZoom: [
      //   {
      //     //X轴滑动条                    {
      //     type: 'slider', //滑动条
      //     show: true, //开启
      //     xAxisIndex: [0],
      //     start: 0, //初始化时，滑动条宽度开始标度
      //     end: 100 //初始化时，滑动条宽度结束标度
      //   }, //X轴内置滑动
      //   {
      //     type: 'inside', //内置滑动，随鼠标滚轮展示
      //     xAxisIndex: [0],
      //     start: 0, //初始化时，滑动条宽度开始标度
      //     end: 100 //初始化时，滑动条宽度结束标度
      //   }
      // ],
      xAxis: {
        axisLine: {
          lineStyle: {
            color: '#ffffff',
            width: 1, //这里是为了突出显示加上的
          },
        },
        name: '(m)',
        nameTextStyle: {
          fontSize: 15,
          padding: [0, 0, 0, -10],
          color: '#ffffff',
        },
        type: 'category',
        data: need_x11,
        // splitArea: {
        //   show: true
        // }
      },
      yAxis: {
        axisLine: {
          lineStyle: {
            color: '#ffffff',
            width: 1, //这里是为了突出显示加上的
          },
        },
        nameTextStyle: {
          fontSize: 10,
          padding: [0, 0, 0, -10],
          color: '#ffffff',
        },
        type: 'category',
        data: days,
        // splitArea: {
        //   show: true
        // }
      },
      legend: {
        left: 'center',
        textStyle: {
          fontSize: 18, //字体大小
          color: '#ffffff', //字体颜色
        },
      },
      visualMap: {
        min: -25,
        max: 25,
        calculable: true,
        orient: 'vertical',
        left: 'right',
        top: 'center',
        realtime: false,
        textStyle: {
          color: '#ffffff',
        },
        inRange: {
          color: [
            'RGB(0,10,255)',
            'RGB(0,150,255)',
            'RGB(0,199,255)',
            '#11fff9',
            'RGB(0,255,0)',
            '#FFF500',
            'RGB(255,230,0)',
            'RGB(249, 102, 72)',
            'RGB(255,0,0)',
          ],
        },
      },
      series: [
        {
          pointSize: 10, // 设置热力图上点的大小
          // name: '带钢板形2D图',
          type: 'heatmap',
          data: res.sort((a: any, b: any) => a[0] - b[0]),
        },
      ],
    };
    //使用刚指定的配置项和数据显示图表。
    // myChart.setOption(option, true)
    //清空画布，防止缓存
    myChart.clear();
    //使用刚指定的配置项和数据显示图表。mouseover
    myChart.setOption(option, true);
    myChart.getZr().on('click', (params) => {
      /* 通过获取echarts上面点击的区域是在第几格，根据索引来判断数据 */
      let pointInPixel = [params.offsetX, params.offsetY];
      var lattice: any = '';
      if (myChart.containPixel('grid', pointInPixel)) {
        var xIndex: any = myChart.convertFromPixel({ seriesIndex: 0 }, pointInPixel)[0];
        var yIndex = myChart.convertFromPixel({ seriesIndex: 0 }, pointInPixel)[1];
        lattice = xIndex + 1;
        clickChanel = yIndex;
        find_singleChanel(formData, clickChanel);
      }
      Tuglie = [];
      for (var x = 0; x < res.length; x++) {
        if (res[x]['0'] == xIndex) {
          Tuglie.push(res[x]);
        }
      }
      var list: any = [];
      // console.log(this.Tuglie.sort((a, b) => a[1] - b[1]))
      list = Tuglie.sort((a, b) => a[1] - b[1])
        .map((item) => {
          return item[2];
        })
        // .reverse()
        .join(',');
      //方程开始
      let newX = list.split(',');
      let zeroPoint = parseInt(newX.length / 2); //取中间点
      let leftX = [];
      let rightX = [];
      //存放X正半轴
      for (let i = 0; i < zeroPoint; i++) {
        leftX.push(parseFloat(((2 * i + 1) / newX.length).toFixed(2)));
      }
      //存放X负半轴
      for (let i = 1; i <= zeroPoint; i++) {
        rightX.push(parseFloat(((-2 * i + 1) / newX.length).toFixed(2)));
      }
      //拼接成一个完整的X轴
      let allXaxis = rightX.reverse().concat(leftX);
      let allYaxis = [];
      allXaxis.forEach((item, index) => {
        // a*x平方+b*x+c
        allYaxis.push(
          parseFloat(rememberA[lattice - 1] * Math.pow(item, 2) * 1 + rememberB[lattice - 1] * item * 1 + rememberC[lattice - 1] * 1).toFixed(2) * 1
        );
      });
      //补齐数组
      for (let i = 0; i < listMxsMin; i++) {
        allYaxis.push('');
        allYaxis.unshift('');
      }
    });
  }
  async function find_singleChanel(extid: any, chanel: any) {
    if (chanel <= 0 || chanel > 26) {
      return;
    }
    let chanel_f = [];
    chanel_f.push('tcm_shape_channe_' + chanel);
    let str = 'tcm_shape_channe_' + chanel;

    const graphParam = {
      line: 'TCM2280',
      extid: [extid],
      curve: chanel_f,
    };
    let res = await historyApi.getgraphData(graphParam);
    //绘制2D板形图曲线-长度序列
    if (Array.isArray(res.data.data.curve[0][str]) && res.data.data.curve[0][str].length > 0) {
      echart_singleChanel(res.data.data.curve[0][str], str, 'app_chanel');
    } else {
      echarts_no('app_chanel');
    }
  }
  // 无数据时：展示暂无数据
  function echarts_no(e: any, height = 400) {
    console.log('e' + e);
    const dom = document.getElementById(e);
    if (dom != null) {
      dom.innerHTML = '暂无数据';
      dom.style.cssText = 'text-align:center; color: #999; border: none;line-height:' + height + 'px';
      dom.removeAttribute('_echarts_instance_');
    }
  }
  function echart_singleChanel(data: any, title: any, id: any) {
    var need_x11 = [];
    var need_y11 = [];
    need_y11 = data;
    for (let i = 0; i <= data.length; i++) {
      need_x11.push(i + 1);
    }
    toolbox.feature.myTool = {
      show: true, //是否显示
      title: '定义y轴', //鼠标悬空的提示文字
      icon: 'path://M659.77002 969.890638 363.679441 969.890638 363.679441 644.667555 33.604864 76.752058l325.225129 0 155.319461 300.952306L669.480172 76.752058 989.844597 76.752058 659.77002 639.812991 659.77002 969.890638z', //这个是阿里icon svg 后 b的全部字符串
      onclick: () => {
        sum = 18;
        dialogVisible2.value = true;
        dialogTitle2.value = '定义Y轴刻度范围';
      },
    };
    var myChart = echarts.init(document.getElementById(id)); //将配置注入到html中定义的容器
    var option = {
      title: {
        text: title,
        textStyle: {
          fontSize: 14,
          color: '#ffffff',
        },
      },
      color: 'yellow',
      // legend: {
      //   x: 'center', //可设定图例在左、右、居
      //   textStyle: {
      //     // fontWeight: 'bolder', 字体加粗
      //     fontSize: 12,
      //     color: '#fff'
      //   },
      //   icon: 'roundRect'
      // },
      toolbox: toolbox,
      tooltip: {
        trigger: 'axis',
      },
      //表头
      grid: {
        left: '3%',
        right: '5%',
        top: '15%',
        bottom: '18%',
        containLabel: true,
      },
      xAxis: {
        axisLine: {
          lineStyle: {
            color: '#ffffff',
          },
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dotted',
          },
        },
        // intercal: 50,
        nameTextStyle: {
          fontSize: 12,
          // padding: [0, -50, 100, 0],
          color: '#ffffff',
        },
        name: '(m)',
        type: 'category',
        data: need_x11,
      },
      yAxis: [
        {
          scale: true, //纵坐标自适应
          axisLine: {
            lineStyle: {
              color: '#ffffff',
            },
          },
          min: echart.min18,
          max: echart.max18,
          type: 'value',
          name: '',
          axisLabel: {
            formatter: '{value}',
            textStyle: {
              color: '#ffffff',
            },
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dotted',
            },
          },
        },
      ],
      series: [
        {
          name: '',
          type: 'line',
          data: need_y11.map((value) => value / 20),
        },
      ],
    };
    myChart.clear();
    myChart.setOption(option);
  }

  function initPlatcmChart(option: any, retry = 0) {
    const chartDom = document.getElementById('platcmLineChartRef');
    if (!chartDom) {
      if (retry < 10) {
        setTimeout(() => {
          initPlatcmChart(option, retry + 1);
        }, 50);
      }
      return;
    }
    if (!platcmChartInstance) {
      platcmChartInstance = echarts.init(chartDom);
    }
    platcmChartInstance.clear();
    platcmChartInstance.setOption(option, true);
  }

  watch(platcmResult, (val) => {
    if (val) {
      nextTick(() => {
        initPlatcmChart(platcmOption.value);
      });
    }
  });

  onUnmounted(() => {
    window.removeEventListener('resize', resizeChart);
    lineChartInstance?.dispose();
    if (platcmChartInstance) {
      platcmChartInstance.dispose();
      platcmChartInstance = null;
    }
  });
</script>

<style scoped>
  /* --- Mostly copied styles --- */
  .quality-judge-container {
    background-color: #0a1a3a;
    color: #c0c4cc;
    padding: 10px;
    height: 100%;
    /* Use 100% for layout within router-view */
    box-sizing: border-box;
    font-family: 'Microsoft YaHei', 'Segoe UI', sans-serif;
    font-size: 13px;
    overflow: hidden;
    scrollbar-width: thin;
    scrollbar-color: #3a5a8a #142a52;
    display: flex;
    flex-direction: column;
  }

  .quality-judge-container > *:not(:last-child):not(.detail-section) {
    margin-bottom: 15px;
  }

  /* --- Search Panel (Ensure styles match LayOutJudge) --- */
  .search-panel {
    background-color: #1c2d5a;
    padding: 10px 15px;
    border-radius: 3px;
    flex-shrink: 0;
  }

  .search-row {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    margin-bottom: 10px;
  }

  .search-row:last-child {
    margin-bottom: 0;
  }

  .search-item {
    display: flex;
    align-items: center;
    margin-right: 15px;
    /* Match LayOutJudge */
    margin-bottom: 10px;
    /* Match LayOutJudge */
  }

  .label {
    color: #c0c4cc;
    margin-right: 8px;
    white-space: nowrap;
    min-width: 65px;
    /* Match LayOutJudge */
    text-align: right;
  }

  :deep(.custom-date-picker.el-date-editor) {
    width: 420px !important;
    /* Match LayOutJudge */
    height: 28px;
    background-color: #0a1a3a;
    border: 1px solid #3a5a8a;
    box-shadow: none;
  }

  /* ... other date picker deep styles ... */

  .range-item .label {
    min-width: 65px;
    /* Match LayOutJudge */
  }

  .range-input {
    width: 80px;
    /* Match LayOutJudge */
  }

  :deep(.range-input .el-input__wrapper) {
    padding-left: 8px;
    padding-right: 8px;
  }

  .separator {
    margin: 0 5px;
    color: #c0c4cc;
  }

  .custom-input,
  .custom-select,
  .range-input,
  :deep(.el-input__wrapper),
  :deep(.el-select__wrapper) {
    height: 28px;
    line-height: 28px;
    background-color: #0a1a3a !important;
    border: 1px solid #3a5a8a !important;
    border-radius: 3px !important;
    color: #c0c4cc !important;
    box-shadow: none !important;
    font-size: 13px !important;
  }

  :deep(.custom-select .el-select__placeholder),
  :deep(.custom-select .el-select__caret) {
    color: #c0c4cc;
  }

  .custom-input {
    width: 150px;
    /* Match LayOutJudge */
  }

  .custom-select {
    width: 120px;
    /* Match LayOutJudge */
  }

  .search-actions {
    margin-left: auto;
    display: flex;
    align-items: center;
    padding-left: 20px;
    /* Match LayOutJudge */
  }

  .btn {
    height: 28px;
    padding: 0 15px;
    border: none;
    border-radius: 3px;
    font-size: 13px;
    cursor: pointer;
    margin-left: 10px;
    color: #fff;
  }

  .query-btn {
    background-color: #2979ff;
  }

  .query-btn:hover {
    background-color: #5393ff;
  }

  .reset-btn {
    background-color: #3a5a8a;
  }

  .reset-btn:hover {
    background-color: #5a7aa4;
  }

  .export-btn {
    background-color: #2979ff;
  }

  .export-btn:hover {
    background-color: #5393ff;
  }

  /* --- Table Panel (Styles should be consistent) --- */
  .table-panel {
    background-color: #1c2d5a;
    padding: 5px;
    border-radius: 3px;
    overflow: hidden;
    flex-grow: 1;
    min-height: 0;
    display: flex;
  }

  :deep(.el-table),
  :deep(.el-table__body),
  :deep(.el-table__header-wrapper),
  :deep(.el-table__body-wrapper) {
    background-color: #1c2d5a !important;
  }
  :deep(.el-table__empty-block) {
    background: linear-gradient(135deg, #183c7e 0%, #0a1a3a 100%) !important;
  }
  :deep(.el-table th),
  :deep(.el-table td) {
    background-color: #1c2d5a !important;
  }
  :deep(.el-table__body tr) {
    background-color: #1c2d5a !important;
  }
  :deep(.el-table__body tr:hover > td) {
    background-color: #223a6b !important;
  }

  /* Table Specific Styles */
  .result-ok {
    color: #67c23a;
    /* Green */
    font-weight: bold;
    background-color: rgba(103, 194, 58, 0.1);
    padding: 2px 6px;
    border-radius: 3px;
  }

  .result-no {
    color: #ff4d4f;
    /* Red */
    font-weight: bold;
    background-color: rgba(255, 77, 79, 0.1);
    padding: 2px 6px;
    border-radius: 3px;
  }

  .action-btn {
    padding: 3px 8px;
    font-size: 12px;
    border: none;
    border-radius: 3px;
    margin: 0 2px;
    cursor: pointer;
    color: #fff;
  }

  .select-btn {
    background-color: #e6a23c;
  }

  /* Yellow */
  .select-btn:hover {
    background-color: #ebb563;
  }

  /* --- Pagination Panel (Styles should be consistent) --- */
  .pagination-panel {
    background-color: #1c2d5a;
    padding: 8px 15px;
    border-radius: 3px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 0;
  }
  :deep(.el-pagination) {
    background-color: transparent !important;
  }
  :deep(.el-pagination__total),
  :deep(.el-pagination__sizes),
  :deep(.el-pagination__jump),
  :deep(.el-pagination__editor),
  :deep(.el-pagination button),
  :deep(.el-pager li) {
    background-color: #1c2d5a !important;
    color: #7ec7ff !important;
    border: none !important;
  }
  :deep(.el-pager li.is-active) {
    background-color: #2979ff !important;
    color: #fff !important;
  }

  /* --- Detail Panel (Styles should be consistent) --- */
  .detail-panel {
    flex-shrink: 0;
    padding: 15px;
    background-color: #0f2142;
    /* Slightly different background for contrast */
    border-radius: 4px;
  }

  .detail-grid {
    display: grid;
    grid-template-columns: auto auto 1fr;
    /* Left, Middle, Right (chart takes rest) */
    gap: 20px;
    align-items: start;
  }

  /* Left and Middle common */
  .detail-left,
  .detail-middle {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }

  /* Left Section */
  .judge-block {
    background-color: #1c2d5a;
    border: 1px solid #3a5a8a;
    border-radius: 3px;
    padding: 10px 15px;
    display: grid;
    grid-template-areas:
      'result result'
      'label1 value1'
      'label2 value2';
    grid-template-columns: auto 1fr;
    gap: 5px 10px;
    align-items: center;
    min-width: 200px;
  }

  .judge-result {
    grid-area: result;
    font-size: 18px;
    font-weight: bold;
    padding-bottom: 5px;
    margin-bottom: 5px;
    border-bottom: 1px solid #3a5a8a;
  }

  .judge-label {
    grid-area: label1 / label1 / label2 / label2;
    color: #a0a3a8;
    font-size: 12px;
  }

  .judge-value {
    grid-area: value1 / value1 / value2 / value2;
    font-weight: bold;
  }

  .judge-content {
    display: contents;
  }

  .judge-score {
    display: contents;
  }

  .judge-content .judge-label {
    grid-area: label1;
  }

  .judge-content .judge-value {
    grid-area: value1;
  }

  .judge-score .judge-label {
    grid-area: label2;
  }

  .judge-score .judge-value {
    grid-area: value2;
  }

  .judge-ok .judge-result {
    color: #67c23a;
  }

  .judge-no .judge-result {
    color: #ff4d4f;
  }

  /* Middle Section */
  .judge-block-small {
    background-color: #1c2d5a;
    border: 1px solid #3a5a8a;
    border-radius: 3px;
    padding: 8px 12px;
    display: flex;
    align-items: center;
    gap: 15px;
    min-width: 240px;
  }

  .judge-result-small {
    font-size: 16px;
    font-weight: bold;
    padding: 5px 10px;
    border-radius: 3px;
  }

  .judge-ok .judge-result-small {
    color: #67c23a;
    background-color: rgba(103, 194, 58, 0.1);
  }

  .judge-no .judge-result-small {
    color: #ff4d4f;
    background-color: rgba(255, 77, 79, 0.1);
  }

  .judge-details {
    display: flex;
    flex-direction: column;
    gap: 2px;
  }

  .detail-item {
    font-size: 12px;
  }

  /* Right Section (Chart) */
  .detail-right {
    /* Inherit .detail-section styles */
    display: flex;
    /* Make it flex container */
    flex-direction: column;
    /* Stack header and chart vertically */
    height: 100%;
    /* Take full height of grid cell */
    background-color: #1c2d5a;
    /* Match other detail sections */
    border-radius: 3px;
    overflow: hidden;
  }

  .section-header {
    background-color: #2979ff;
    color: #fff;
    padding: 8px 15px;
    font-weight: bold;
  }

  .chart-container {
    flex-grow: 1;
    /* Allow chart container to fill space */
    min-height: 200px;
    /* Ensure minimum height */
    padding: 10px;
  }

  :deep(.el-table--border .el-table__inner-wrapper::after),
  :deep(.el-table--border::after),
  :deep(.el-table--border::before),
  :deep(.el-table__border-left-patch),
  :deep(.el-table--border .el-table__inner-wrapper::before) {
    z-index: -1;
  }

  :deep(.el-table td.el-table__cell),
  :deep(.el-table th.el-table__cell.is-leaf) {
    border-bottom: 1px solid #06279d !important;
  }
  :deep(.el-table--border td.el-table__cell),
  :deep(.el-table--border th.el-table__cell) {
    border-right: 1px solid #06279d !important;
  }
</style>
